export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations: {
    addToCart(state, goods) {
      const finalRes = state.cart.find(x => {
        return x.goods_id === goods.goods_id
      })
      if (finalRes) {
        finalRes.goods_count++
      } else {
        state.cart.push(goods)
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateGoodsState(state, goods) {
      const res = state.cart.find(x => x.goods_id == goods.goods_id)
      res.goods_state = goods.goods_state
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsCount(state, goods) {
      const res = state.cart.find(x => x.goods_id == goods.goods_id)
      res.goods_count = goods.goods_count;
      this.commit('m_cart/saveToStorage')
    },
    deleteByGoodsId(state, goods_id) {
      state.cart = state.cart.filter(x => goods_id !== x.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateAllGoodsState(state, goods_state) {
      state.cart.forEach((item) => {
        item.goods_state = goods_state
      })
      this.commit('m_cart/saveToStorage')
    }

  },
  getters: {
    total(state) {
      let count = 0
      state.cart.forEach(item =>
        count = count + item.goods_count
      )
      return count
    },
    totalMoney(state) {
      return state.cart.filter((item) => item.goods_state).reduce((total, item) => {
        return total += item.goods_price * item.goods_count
      }, 0)
    },
    totalCheckCount(state) {
      return state.cart.filter((item) => item.goods_state).reduce((total, item) => {
        return total += item.goods_count
      }, 0)
    }
  }
}